package com.example.server.controller;


import com.example.server.common.Result;
import com.example.server.entity.User;
import com.example.server.service.CaptchaService;
import com.example.server.service.UserService;
import com.example.server.utils.FileUploadUtil;
import com.example.server.utils.JwtUtil;
import com.example.server.utils.MD5Util;
import com.example.server.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
//@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CaptchaService captchaService;

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    //注册
    @PostMapping("/register")
    public Result register(@RequestParam @NotNull(message = "邮箱不能为空") @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") String email,
                           @RequestParam @Pattern(regexp = "^(?=.*[a-zA-Z])(?=.*\\d).{8,}$", message = "密码必须包含数字和字母，且长度至少8位") String password,
                           @RequestParam @Pattern(regexp = "^\\S{1,10}$", message = "昵称必须为1~10个字符") String username) {
        //检查邮箱和昵称是否被占用
        User u = userService.findByEmail(email);
        if (u != null) {
            return Result.error("该账号已注册");
        }
        u = userService.findByUsername(username);
        if (u != null) {
            return Result.error("该昵称已被占用");
        }
        //允许注册
        userService.register(email, password, username);
        return Result.success();
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestParam @NotNull(message = "账号不能为空") String email,
                        @RequestParam @NotNull(message = "密码不能为空") String password) {

        //查询用户
        User u = userService.findByEmail(email);
        if (u == null) {
            return Result.error("账号或密码错误");
        }
        //判断密码是否正确
        if (MD5Util.md5(password).equals(u.getPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("username", u.getUsername());
            claims.put("role", u.getRole());
            String token = JwtUtil.genToken(claims);
            userService.updateLastLogin(u.getId());
            return Result.success(token);
        }
        return Result.error("账号或密码错误");
    }


    //返回当前用户信息
    @GetMapping("/user/userInfo")
    public Result getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = userService.findById(id);
        return Result.success(user);
    }



    //更新昵称
    @PatchMapping("/user/modifyName")
    public Result updateUserName(@RequestParam @Pattern(regexp = "^\\S{1,10}$", message = "昵称必须为1~10个字符") String username) {
        //检查昵称是否被占用
        User u = userService.findByUsername(username);
        if (u != null) {
            return Result.error("该昵称已被占用");
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        String role = (String) map.get("role");
        userService.updateUsername(username,userId);
        //重新生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userId);
        claims.put("username", username);
        claims.put("role", role);
        String token = JwtUtil.genToken(claims);
        return Result.success(token);
    }

    //修改密码
    @PatchMapping("/user/modifyPwd")
    public Result updatePassword(@RequestBody Map<String, String> pwds) {
        String oldPwd = pwds.get("oldPassword");
        String newPwd = pwds.get("newPassword");
        String confirmPwd = pwds.get("confirmPassword");
        //检查输入是否为空
        if(oldPwd == null || oldPwd.trim().isEmpty() || newPwd == null || newPwd.trim().isEmpty() || confirmPwd == null || confirmPwd.trim().isEmpty()) {
            return Result.error("密码不能为空");
        }
        //检查原密码是否正确
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        User loginUser = userService.findById(userId);
        if (!loginUser.getPassword().equals(MD5Util.md5(oldPwd))) {
            return Result.error("原密码填写不正确");
        }
        //检查新密码是否符合规范
        String passwordRegex = "^(?=.*[a-zA-Z])(?=.*\\d).{8,}$";
        if(!java.util.regex.Pattern.compile(passwordRegex).matcher(newPwd).matches()){
            return Result.error("密码必须包含数字和字母，且长度至少8位");
        }
        //检查确认密码是否与新密码一致
        if(!confirmPwd.equals(newPwd)){
            return Result.error("确认密码与新密码不一致");
        }
        //完成更新
        userService.updatePassword(newPwd);
        return Result.success();
    }

    //上传头像
    @PostMapping("/user/uploadAvatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            String avatarUrl ="http://" + ip + ":" + port + "/"
                    + FileUploadUtil.saveImageFile(file, "avatars", String.valueOf(userId), "jpg");
            userService.updateAvatar(userId, avatarUrl);
            return Result.success(avatarUrl);
        } catch (Exception e) {
            return Result.error("头像上传失败：" + e.getMessage());
        }
    }

    /*仅限管理员*/
    //返回所有用户
    @GetMapping("/user/selectAll")
    public Result getAllUsers() {
        //验证是否是管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        String role = (String) map.get("role");
        if (role == null || !role.equals("admin")) {
            return Result.error("没有权限");
        }
        // 获取所有用户
        List<User> users = userService.getAllUsers();
        return Result.success(users);
    }

    //修改指定用户的身份
    @PatchMapping("/user/changeRole")
    public Result changeRole(@RequestParam Integer id, @RequestParam String role){
        //验证是否是管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        String curRole = (String) map.get("role");
        Integer userId = (Integer) map.get("id");
        if (curRole == null || !curRole.equals("admin")) {
            return Result.error("没有权限");
        }
        //检查参数
        if(role == null || !role.equals("admin")&&!role.equals("user")){
            return Result.error("参数无效");
        }
        if(userId.equals(id)){//避免误操作自身
            return Result.error("请勿修改自身身份");
        }
        User u = userService.findById(id);
        if (u == null) {
            return Result.error("参数无效");
        }
        userService.changeRole(id, role);
        return Result.success();
    }

    //删除指定用户
    @DeleteMapping("/user/deleteUser")
    public Result DeleteUser(@RequestParam Integer id){
        //验证是否是管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        String curRole = (String) map.get("role");
        Integer userId = (Integer) map.get("id");
        if (curRole == null || !curRole.equals("admin")) {
            return Result.error("没有权限");
        }
        if(userId.equals(id)){//避免误删除自身
            return Result.error("请在个人主页注销");
        }
        User u = userService.findById(id);
        if (u == null) {
            return Result.error("用户不存在");
        }
        userService.deleteUser(id);
        return Result.success();
    }

    // 发送验证码
    @PostMapping("/sendCaptcha")
    public Result sendCaptcha(@RequestParam @NotNull(message = "邮箱不能为空") @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") String email) {
        try {
            boolean result = captchaService.sendCaptcha(email); // 调用验证码服务
            if (result) {
                return Result.success("验证码发送成功");
            } else {
                return Result.error("验证码发送失败，请稍后重试");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage()); // 返回服务抛出的错误信息
        } catch (Exception e) {
            return Result.error("发送验证码时发生异常：" + e.getMessage());
        }
    }
    //验证邮箱验证码
    @PostMapping("/verifyCaptcha")
    public Result verifyCaptcha(
            @RequestParam @NotNull(message = "邮箱不能为空") @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") String email,
            @RequestParam @NotNull(message = "验证码不能为空") @NotBlank(message = "验证码不能为空") String captcha) {
        try {
            boolean isValid = captchaService.verifyCaptcha(email, captcha);
            if (isValid) {
                return Result.success("验证码验证成功");
            } else {
                return Result.error("验证码验证失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("验证验证码时发生异常：" + e.getMessage());
        }
    }

}
